package com.example.xwweibo.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xwcommon.entity.Comment;
import com.example.xwcommon.entity.User;
import com.example.xwcommon.entity.Weibo;
import com.example.xwcommon.service.CommentService;
import com.example.xwcommon.service.UserService;
import com.example.xwcommon.service.WeiboService;
import com.example.xwcommon.vo.Response;
/*import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;*/
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class WeiboApi {
    @Autowired
    @Qualifier("weiboService")
    private WeiboService weiboService;
    @Autowired
    @Qualifier("com.example.xwcommon.service.UserService")
    private UserService userService;
    @Autowired
    @Qualifier("commentService")
    private CommentService commentService;
    @Value("${fileLocation.uploag_location}")
    private String upload_location;
    @Autowired
    private RedisTemplate<String, Response<Page<Weibo>>> redisTemplate;
    private static final String CACHE_KEY_PREFIX = "weibo:list:";

    @RequestMapping("/api/weibo/addWeibo")
    @GlobalTransactional
    public ResponseEntity<Response<Weibo>> addWeibo(String userName, String title, String content, MultipartFile photo, HttpSession session) throws IOException, TransactionException {
        String photoName=photo.getOriginalFilename();
        if(!photo.isEmpty()){
            photoName= UUID.randomUUID().toString()+photoName.substring(photoName.lastIndexOf("."));
            if(!new File(upload_location).exists()){
                new File(upload_location).mkdirs();
            }
            photo.transferTo(new File(upload_location +"/"+ photoName));
        }
        try{
            Response<Weibo> response = weiboService.addWeibo(userName,title,content,photoName);
            if(response.getCode() == 200){
                User user = (User) session.getAttribute("cur_user");
                user.setScore(user.getScore()+10);
                userService.addScore(user.getLoginName(),user.getScore());
                session.setAttribute("cur_user",user);
                return ResponseEntity.ok(response);
            }
        }catch (RuntimeException e){
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }

    @RequestMapping("/api/weibo/getWeiboById")
    public ResponseEntity<Response<Weibo>> getWeiboById(Integer weiboId){
        Response<Weibo> response = weiboService.getWeiboById(weiboId);
        if(response.getCode() == 200){
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }
    @RequestMapping("/api/weibo/getWeiboListByLoginName")
    public ResponseEntity<Response<Page<Weibo>>> getWeiboListByLoginName(Integer pageNum, Integer pageSize, String loginName, Integer state){
        Response<Page<Weibo>> response = weiboService.getWeiboListByLoginName(pageNum,pageSize,loginName,state);
        if(response.getCode() == 200){
            for(Weibo weibo: response.getData().getRecords()){
                List<Comment> commentList = commentService.showListByWeibo(weibo.getWeiboId(), 1, 10, state).getData().getRecords();
                commentList.sort(new Comparator<Comment>() {
                    @Override
                    public int compare(Comment c1, Comment c2) {
                        return c1.getCreateTime().compareTo(c2.getCreateTime());
                    }
                });
                User user = userService.getUserByLoginName(weibo.getUserName()).getData();
                Map<String, Object> map = new HashMap<>();
                map.put("user",user);
                map.put("commentList",commentList);
                weibo.setMap(map);
            }
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }
    @RequestMapping("/api/weibo/list")
    public ResponseEntity<Response<Page<Weibo>>> list(Integer pageNum, Integer pageSize, String findtxt, Integer state){
        //读取redis缓存

        Response<Page<Weibo>> response = weiboService.list(pageNum,pageSize,findtxt,state);
        if(response.getCode() == 200){

            List<Weibo> weiboList = response.getData().getRecords();
            for(Weibo weibo: weiboList){
                List<Comment> commentList = commentService.showListByWeibo(weibo.getWeiboId(), 1, 10, state).getData().getRecords();
                commentList.sort(new Comparator<Comment>() {
                    @Override
                    public int compare(Comment c1, Comment c2) {
                        return c1.getCreateTime().compareTo(c2.getCreateTime());
                    }
                });
                User user = userService.getUserByLoginName(weibo.getUserName()).getData();
                Map<String, Object> map = new HashMap<>();
                map.put("user",user);
                map.put("commentList",commentList);
                weibo.setMap(map);
            }
            response.getData().setRecords(weiboList);
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }
    @RequestMapping("/api/weibo/updateReadCount")
    public ResponseEntity<Response<Weibo>> updateReadCount(Integer weiboId){
        Response<Weibo> response = weiboService.updateReadCount(weiboId);
        if(response.getCode() == 200){
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }
    @RequestMapping("/api/weibo/updateState")
    public ResponseEntity<Response<Weibo>> updateState(Integer weiboId, Integer state){
        Response<Weibo> response = weiboService.updateState(weiboId,state);
        if(response.getCode() == 200){
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(response);
    }
    @RequestMapping("/api/weibo/deleteWeibo")
    public ResponseEntity<Response<Weibo>> deleteWeibo(Integer weiboId){
        Response<Weibo> response = weiboService.deleteWeibo(weiboId);
        Response<Page<Comment>> commentResponse = commentService.showListByWeibo(weiboId,1,100,1);
        for(Comment comment : commentResponse.getData().getRecords()){
            if(commentService.removeComment(comment.getCommentId()).getCode()!=200){
                return ResponseEntity.status(500).body(new Response<>(505,"事务错误，正在回滚",null));
            }
        }
        if(response.getCode() == 200){
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }
    @RequestMapping("/api/weibo/getWeiboCountByLoginName")
    public ResponseEntity<Response<Integer>> getWeiboCountByLoginName(String loginName, Integer state){
        Response<Integer> response = weiboService.getWeiboCountByLoginName(loginName,state);
        if(response.getCode() == 200){
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.status(500).body(new Response<>(500,"参数错误",null));
    }

}
